<template>
  <div class="updateWXOpenId">
    <div class="updateWXOpenIdDiv">
      <el-form v-model="form">
        <el-form-item prop="phone" class="el-form-item__white">
          <el-input v-model="form.phone" placeholder="手机号" />
        </el-form-item>
        <el-form-item prop="verificationCode">
          <el-input placeholder="验证码" v-model="form.verificationCode" @keypress.enter.native="bind"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getAuthCode" v-show="show">获取验证码</el-button>
          <span v-show="!show">{{count}}s</span>
        </el-form-item>
        <el-form-item>
          <el-button @click="bind">绑定</el-button>
        </el-form-item>
      </el-form>
      <!-- 登陆拦截判断 -->
      <!--   <el-dialog
            :visible="isShowDialog"
            title="请先选择角色"
            width="60%"
            @close="handleClose"
            left>
            <div class="wrapScroll">
                <p  style=""
                v-for="(item,index) of selectionRole"
                :key="index"
                @click="setUserRoleHandle(item)">
                    <router-link class="dialogP" to="">
                    公司：{{item.dealerName}}&nbsp;&nbsp;&nbsp;&nbsp;--
                    部门：{{item.orgName}}&nbsp;&nbsp;&nbsp;&nbsp;--
                    角色：{{item.roleName}}
                    </router-link>
                </p>
            </div>
      </el-dialog>-->

      <!-- 角色切换 -->
      <BaseDialog :visible.sync="isShowDialog" title="请您先选择职位" destroyOnClose>
        <div class="wrapScroll">
          <div
            class="dialogP"
            style
            v-for="(item,index) of selectionRole"
            :key="index"
            @click="setUserRoleHandle(item)"
          >
            <router-link to="./">
              <!-- 公司：{{item.dealerName}}&nbsp;&nbsp;&nbsp;&nbsp;-- -->
              <h3>{{item.orgName}}</h3>
              <!-- &nbsp;&nbsp;&nbsp;&nbsp;-- -->
              <p>{{item.roleName}}</p>
            </router-link>
          </div>
          <div style="text-align: center;margin-top: 30px;">
            <el-button @click="handleClose">返回</el-button>
            <!-- <el-button  type="primary">确定</el-button> -->
          </div>
        </div>
      </BaseDialog>
      <a v-show="false" href="/login" ref="login"></a>
    </div>
  </div>
</template>
<script>
import store from '@/store';
import { mapActions, mapState } from 'vuex';
import * as types from '@/api/login/types';
import { sleep } from '@/utils';
import { setToken, setDataType, setAppId, jsEncrypt } from '@/assets/js/auth';
import { sendSms, accountBinding, doLogin, initLogin, getUserInfo, sendPhoneCode, roleDetail, setUserRole, weChatLogin } from '@/api/login/index';
import pc_cyxBg from '@/assets/img/login1.png';
import pc_cyx from '@/assets/img/login.png';
export default {
  name: 'updateWXOpenId',
  props: ['openid'],
  data() {
    return {
      form: {
        phone: '',
        verificationCode: '',
        openid: '',
        appId: '',
        city: '',
        country: '',
        headimgurl: '',
        nickname: '',
        province: '',
        sex: '',
        type: '',
        unionid: ''
      },
      editableTabs: [
        {
          title: '首页',
          name: 'web000',
          url: '/home',
          code: 'web000',
          closable: false
        }
      ],
      count: '',
      timer: null,
      show: true,
      getVerCode: '',
      selectionRole: [],
      isShowDialog: false,
      pc_cyx: pc_cyx
    };
  },
  computed: {
    ...mapState('app', ['btnLoading'])
  },
  methods: {
    ...mapActions('app', ['createLoginInfo']),
    bind() {
      // if(this.form.verificationCode != this.getVerCode){
      //   this.$message({message:'验证码输入有误，请重新输入！',type:'warning',showClose:true,})
      //   return;
      // }
      if (localStorage.getItem('openidwx')) {
        this.form.openidwx = localStorage.getItem('openidwx');
        this.form.city = localStorage.getItem('city');
        this.form.country = localStorage.getItem('country');
        this.form.headimgurl = localStorage.getItem('headimgurl');
        this.form.nickname = localStorage.getItem('nickname');
        this.form.province = localStorage.getItem('province');
        this.form.sex = localStorage.getItem('sex');
        this.form.type = localStorage.getItem('type');
        this.form.unionid = localStorage.getItem('unionid');
        this.form.openid = localStorage.getItem('openidwx');
        (this.form.appId = localStorage.getItem('appId') ? localStorage.getItem('appId') : 'cyx'),
          accountBinding(this.form).then(res => {
            if (res.resultCode == 200) {
              this.$message({ message: '绑定成功！', type: 'success', showClose: true });
              let _this = this;
              _this.doLogin(res.data);
              // setTimeout(function() {
              //   _this.$refs.login.click();
              // }, 2000);
            } else {
              this.$message({ message: res.errMsg, type: 'warring', showClose: true });
            }
          });
      }
    },
    getAuthCode() {
      //校验手机
      var myreg = /^[1][3-9][0-9]{9}$/;
      if (this.form.phone == null || this.form.phone == '') {
        this.$message('请输入手机号！');
        return;
      } else if (!myreg.test(this.form.phone)) {
        this.$message('输入手机号码格式不正确，请重新输入！');
      } else {
        const TIME_COUNT = 60;
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.show = true;
              // Cookies.set('verificationCode', '');
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000);
        }
        let params = {
          phone: this.form.phone,
          appId: localStorage.getItem('appId') ? localStorage.getItem('appId') : 'cyx'
        };
        //获取验证码后可以进行下一步操作
        sendSms(params).then(res => {
          if (res.resultCode == 200) {
            this.form.openid = res.data.openid;
            this.$message.success('获取验证码成功，请输入验证码！');
          } else {
            // this.getVerCode = res.data.verificationCode;
            // console.log('验证码为：' + this.getVerCode);
          }
        });
      }
    },
    /*修改登录*/
    async doLogin(data) {
      if (data) {
        const res = await doLogin({
          openId: localStorage.getItem('openidwx'),
          loginType: 3,
          appId: data.appId
        });
        console.log(res, 'res');
        if (res.resultCode === 200) {
          setToken(res.data.jwt);
          setDataType(res.data.rData.dataType);
          // 登录成功后判断角色
          // if(this.isShowDialog){
          this.selectionRole = [];
          roleDetail()
            .then(res => {
              res.data.forEach(x => {
                this.selectionRole.push(x);
              });
              console.log(this.selectionRole.length, 'selectionRole');
              if (this.selectionRole.length <= 1) {
                console.log(123, this.selectionRole[0], 'this.selectionRole');
                this.isShowDialog = false;
                this.setUserRoleHandle(this.selectionRole[0]);
              } else {
                this.isShowDialog = true;
              }
            })
            .catch(err => {});
          // }
        } else if (res.resultCode === 998) {
          // this.isCodeImg=true
          console.log(
            res.errMsg
              .split(',')[1]
              .split(':')[1]
              .split('"')[1]
          );
          let base64Img = res.errMsg
            .split(',')[1]
            .split(':')[1]
            .split('"')[1];
        }
      }
    },
    //保存角色
    setUserRoleHandle(data) {
      localStorage.setItem('roleType', data.roleType);
      setUserRole(data).then(res => {
        if (res.resultCode == 200) {
          this.initUserInfo();
        }
      });
    },
    async initUserInfo() {
      await initLogin();
      const {
        data: { userInfo }
      } = await getUserInfo();
      this.createLoginInfo({
        id: userInfo.userId,
        name: userInfo.userName
      });
      // this.createLoginInfo();
      const userAppId = await getUserInfo();
      if (userAppId.resultCode == 200) {
        setAppId(userInfo.appId);
        localStorage.setItem('appId', userInfo.appId);
      }
      await sleep(100);
      this.$router.push({ path: '/' });
    },
    // 关闭
    handleClose() {
      this.isShowDialog = false;
      this.checks = false;
      setToken();
      setDataType();
      sleep(0);
    }
  },
  mounted() {
    /* this.form.openid = Cookies.get('openidwx');
    if (this.form.openid == ('' || null)) {
      this.$refs.login.click();
    } */
  }
};
</script>
<style lang="less" scoped>
.updateWXOpenId {
  width: 100%;
  height: 100%;
  background: url(../../assets/img/login1.png) left top no-repeat;
  background-size: 100%;
  .updateWXOpenIdDiv {
    width: 300px;
    margin: 0 auto;
    padding-top: 150px;
  }
}
.wrapScroll {
  max-height: 300px;
  overflow-y: scroll;
}
.dialogP {
  font-size: 17px;
  line-height: 50px;
  padding-left: 10px;
  a {
    display: block;
    h3 {
      color: #666;
      font-weight: 900;
    }
    p {
      height: 26px;
      line-height: 20px;
      font-size: 14px;
      margin-left: 10px;
    }
  }
}
.dialogP:hover {
  border: 1px solid #1682e6;
  h3 {
    color: #1682e6;
  }
}
</style>


